package blockchain

import (
	"context"
	"fmt"
	"private-domain-overseas-service/tools/ent/hzintegralwallet"
	"time"

	"private-domain-overseas-service/app/business/api/internal/repository/blockchain"
	"private-domain-overseas-service/app/business/api/internal/repository/integral"
	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/app/business/api/internal/types"
	mycommon "private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/status/bizblockchain"
	"private-domain-overseas-service/pkg/status/bizintegral"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzblockchainwallet"
	"private-domain-overseas-service/tools/ent/predicate"

	"github.com/ethereum/go-ethereum/common"
	"github.com/zeromicro/go-zero/core/logx"
)

type BlockchainWalletTransferLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewBlockchainWalletTransferLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BlockchainWalletTransferLogic {
	return &BlockchainWalletTransferLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BlockchainWalletTransferLogic) BlockchainWalletTransfer(req *types.BlockchainWalletTransferRequest) (err error) {
	integralWalletDao := integral.NewIntegralWalletDao(l.ctx, l.svcCtx)
	blockchainWalletDao := blockchain.NewBlockchainWalletDao(l.ctx, l.svcCtx)
	integralWalletRecordDao := integral.NewIntegralWalletRecordDao(l.ctx, l.svcCtx)
	blockchainWalletRecordDao := blockchain.NewBlockchainWalletRecordDao(l.ctx, l.svcCtx)

	// 验证接收地址
	if !common.IsHexAddress(req.Address) {
		return xerr.ErrCodeMsg(xerr.ServerApiInvalidWalletAddressError, fmt.Sprintf("无效的以太坊地址"))
	}

	// 判断兑换数量
	if req.Amounts <= 0 {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("兑换数量必须大于0"))
	}

	// 获取用户ID
	userID := mycommon.JwtAuthUserId(l.ctx)
	// 百分之一
	//baiDecimal := decimal.NewFromInt32(100)
	// 手续费（千分之一）
	//gasPriceRate := decimal.NewFromFloat(constant.GasPriceRate)
	// 计算积分转换
	//actualAmount := decimal.NewFromFloat32(float32(req.Amounts)).Mul(baiDecimal)
	// 计算手续费
	//estimatedGasFeeHzb := actualAmount.Mul(gasPriceRate)
	// 计算到慧赚币
	//hzbCoin := actualAmount.Sub(estimatedGasFeeHzb).Mul(baiDecimal).IntPart()
	hzbCoin := req.Amounts
	if hzbCoin <= 0 {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("兑换数量必须大于手续费"))
	}
	// 生成记录编号
	recordNumber := mycommon.GenerateRandomNumber(18)

	// 查询用户积分钱包
	integralWalletConditions := make([]predicate.HzIntegralWallet, 0)
	integralWalletConditions = append(integralWalletConditions, hzintegralwallet.UserIDEQ(userID))
	integralWalletInfo, err := integralWalletDao.IntegralWalletConditionsOnly(integralWalletConditions)
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("查询用户积分失败:%v", err.Error()))
	}
	// 检查积分余额（包含手续费）
	if integralWalletInfo.WalletActiveBalance < req.Amounts {
		return xerr.ErrCodeMsg(xerr.ServerApiIntegralNotEnoughError, fmt.Sprintf("无效的以太坊地址"))
	}

	// 检查地址是否存在
	blockchainWalletConditions := make([]predicate.HzBlockchainWallet, 0)
	blockchainWalletConditions = append(blockchainWalletConditions, hzblockchainwallet.WalletAddressEQ(req.Address))
	walletInfo, err := blockchainWalletDao.BlockchainWalletConditionsOnly(blockchainWalletConditions)
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询区块链钱包记录失败:%v", err.Error()))
	}

	// 使用事务处理转账操作
	err = mycommon.WithTx(l.ctx, l.svcCtx.Orm, func(tx *ent.Tx) error {
		// 更新用户积分余额
		integralWalletInfo.WalletActiveBalance = integralWalletInfo.WalletActiveBalance - req.Amounts
		if err = integralWalletDao.UpdateIntegralWallet(tx, integralWalletInfo); err != nil {
			logx.Errorf("更新积分余额失败：%v", err)
			return err
		}

		// 创建积分钱包记录
		createIntegralWalletRecord := &ent.HzIntegralWalletRecord{
			UserID:              userID,
			IntegralWalletID:    int64(integralWalletInfo.ID),
			RecordTitle:         "区块链转账",
			RecordNumber:        recordNumber,
			RecordAmount:        req.Amounts,
			RecordStatus:        bizintegral.Disburse,
			RecordType:          bizintegral.DigitalCurrencyType, // 数字货币兑换类型
			RecordActiveBalance: integralWalletInfo.WalletActiveBalance - req.Amounts,
			RecordFreezeBalance: integralWalletInfo.WalletActiveBalance - req.Amounts,
			CreatedAt:           time.Now().Unix(),
		}
		if err = integralWalletRecordDao.CreateIntegralWalletRecord(tx, createIntegralWalletRecord); err != nil {
			return err
		}

		// 创建区块链钱包记录
		createBlockchainWalletRecord := &ent.HzBlockchainWalletRecord{
			UserID:               userID,
			BlockchainWalletID:   int64(walletInfo.ID),
			RecordTitle:          "区块链转账",
			RecordNumber:         recordNumber,
			RecordIntegralAmount: req.Amounts,
			RecordHzbCoin:        hzbCoin,
			RecordRates:          1, // 1:1兑换
			//RecordServiceCharge:  estimatedGasFeeHzb.IntPart(),
			RecordServiceCharge: 0,
			RecordStatus:        bizblockchain.AuditStatus,
			RecordWalletAddress: req.Address,
		}
		_, err = blockchainWalletRecordDao.CreateBlockchainWalletRecord(tx, createBlockchainWalletRecord)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("转账事务处理失败：%v", err))
	}

	// 记录转账日志
	//l.Infof("用户 %d 向地址 %s 转账 %d 积分，手续费 %d", userID, req.Address, req.Address, estimatedGasFeeHzb)
	l.Infof("用户 %d 向地址 %s 转账 %d 积分，手续费 %d", userID, req.Address, req.Address, 0)
	return nil
}
